package com.itany;

import redis.clients.jedis.Jedis;

public class RedisDemo1 {

    //获取锁的等待重试时间
    private  static long waitTimeOut=10000;
    //获取锁的超时时间
    private static Integer timeOut=10000;


    /**
     * 获取分布式锁
     * @return
     */
    public  static boolean getRedisLock(String lockName,String val){
        try {
             //声明jedis对象
            Jedis jedis = new Jedis("127.0.0.1",6379);
            //计算获取锁的时间
            Long endTime = System.currentTimeMillis()+waitTimeOut;
            //尝试获取锁对象
            while (System.currentTimeMillis()<endTime){
                if(jedis.setnx(lockName,val)==1){
                    jedis.expire(lockName,timeOut);
                    return  true;
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return  false;
    }


    /**
     * 释放分布式锁方法
     */
    public static void unRedisLock(String lockName){
        //声明jedis对象
        Jedis jedis = new Jedis("127.0.0.1",6379);
         try {
              jedis.del(lockName);
         }catch (Exception e){
             e.printStackTrace();
         }
    }

    public static void main(String[] args) {
        for(int i=0;i<3;i++){
             Thread td= new Thread(new Test());
             td.setName("Test"+i);
             td.start();
        }
    }
}
